<template>
  <div class="message">
      <div class="tool">
          <!-- 搜索列表 -->
          <div class="search">
          <el-date-picker
              v-model="queryParmas.queryDate"
              type="date"
              placeholder="选择日期"
              :disabled-date="disabledDate"
              @change="toSearch"
              clearable
          />
          <el-input
              v-model="queryParmas.keywords"
              style="width: 240px;margin-left: 10px;"
              placeholder="关键字查询"
              clearable
              @clear="queryKeyword"
              @keyup.enter="queryKeyword"
          >
            <template #suffix>
              <el-icon @click="queryKeyword" style="cursor: pointer;">
                <Search />
              </el-icon>
            </template>
          </el-input>
          
        </div>
        <div class="selectType">
            <el-select v-model="queryParmas.queryType" class="m-2" placeholder="选择一种状态进行查询">
               <el-option v-for="(item,index) in labelList" :value="item.value" :label="item.label" :key="index">
              </el-option>
            </el-select>
            <el-button type="primary" style="margin-left: 10px;" @click="query_by_state">查询</el-button>
        </div>
    </div>
      <div class="table">
          <div class="table-container">
              <el-table 
                  :data="stateList"
                  border 
                  stripe
                  :default-sort="{prop: 'createdAt', order: 'descending'}"
              >

       <el-table-column type="index" label="#"></el-table-column>
              <el-table-column width="250px" sortable prop="createdAt">
                  <template #header>
                      报警时间
                  </template>
                  <template #default="{row}">
                      <i class="iconfont icon-shizhongclock74" style="font-size: 16px;margin-right: 5px;"></i> {{ filterDate(row.createdAt)  }}
                  </template>
      </el-table-column>  
      <el-table-column prop="gateway_name" label="名称" show-overflow-tooltip>
      </el-table-column>
      <el-table-column prop="gateway_ip" label="IP地址" width="120px">
      </el-table-column>
      <el-table-column label="设备名称" width="320px" show-overflow-tooltip>
        <template #default="scope">
          <span class="device-name">{{ getDeviceName(scope.row.gateway_ip, scope.row.module_id) }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="type_id" label="传感器类型" width="120px">
        <template #default="scope">
          <el-tag v-if="scope.row.type_id === 0" type="danger">温度</el-tag>
          <el-tag v-if="scope.row.type_id === 1" type="warning">湿度</el-tag>
          <el-tag v-if="scope.row.type_id === 2" type="success">压力</el-tag>
          <el-tag v-if="scope.row.type_id === 3" type="success">红外</el-tag>
          <el-tag v-if="scope.row.type_id === 4" type="success">紫外</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="info" label="报警内容" width="300px">
      </el-table-column>
      <el-table-column label="状态" prop="state" width="120px">
          <template #default="{row}">
              <div v-if="row.state === 0">
                  <span class="circle-danger"></span>
                  <el-link type="danger">待解决</el-link>
              </div>
              <div v-if="row.state === 1">
                  <span class="circle-primary"></span>
                  <el-link type="primary">进行中</el-link>
              </div>
              <div v-if="row.state === 2">
                  <span class="circle-success"></span>
                  <el-link type="success">已解决</el-link>
              </div>
          </template>
      </el-table-column>
      <el-table-column width="160px">
          <template #header>操作</template>
          <template #default="{row}">
              <el-link type="primary" style="margin-right: 15px;" @click="openConfig(row.state,row.rid)">配置</el-link>
              <el-popconfirm 
                  title="是否要忽视掉这次报警记录"
                  confirm-button-text="确定"
                  cancel-button-text="取消"
                  @confirm="deleteState(row.rid)"
              >
                  <template #reference>
                      <el-link type="danger">忽略</el-link>
                  </template>
              </el-popconfirm>
          </template>
      </el-table-column>
              </el-table>
          </div>
          <!-- 分页 -->
          <div class="pagination-wrapper">
              <el-pagination
                      v-model:current-page="currentPage"
                      v-model:page-size="queryParmas.pageSize"
                      :page-sizes="[5,10]"
                      layout="total, sizes, prev, pager, next, jumper"
                      :total="total"
                      @size-change="handleSizeChange"
                      @current-change="handleCurrentChange"
                  />
          </div>
      </div>
  </div>

  <!-- 配置应用程序 -->
  <el-dialog
  v-model="configExe"
  title="配置"
  width="500"
>
<header id="state_update" style="padding: 10px;">状态变更</header>
<el-radio-group v-model="config_radio">
  <el-radio :value="0">待解决</el-radio>
  <el-radio :value="1">进行中</el-radio>
  <el-radio :value="2">已解决</el-radio>
</el-radio-group>
  <template #footer>
    <div class="dialog-footer">
      <el-button @click="configExe = false">取消</el-button>
      <el-button type="primary" @click="confirm_update_state(row)">
        确定
      </el-button>
    </div>
  </template>
</el-dialog>
</template>

<script lang="ts" setup>
import {Delete,Search} from '@element-plus/icons-vue'
import { ref, onMounted, reactive, getCurrentInstance } from 'vue'
import { channelNameDb } from '../../local/channelNameDb'
import { IhttpReturn } from '../../utils/interface';
  let {proxy} = getCurrentInstance()
  /** 关于数据查询的方面的 */
  let currentPage = ref(1)

  let queryParmas = reactive({
      pageSize: 10,
      page: 1,
      queryDate: "",
      queryType: "",
      keywords: ""
  })
  let stateList = ref([]) // 报警信息列表
  let total = ref(0) // 总数
  
  // 设备名称映射
  const deviceNameMap = ref<Map<string, string>>(new Map())
    // 对时间函数的过滤
  let filterDate = (date:Date) => {
      return new Date(date).toLocaleDateString().replace(/\//g,"-")+' ' + new Date(date).toLocaleTimeString()
   }
   
   // 获取设备名称
   const getDeviceName = (gatewayIp: string, moduleId: string) => {
       const key = `${gatewayIp}-${moduleId}`
       return deviceNameMap.value.get(key) || `监测点${moduleId}`
   }
   
   // 加载设备名称映射
   const loadDeviceNames = async () => {
       try {
           const nameMap = await channelNameDb.getAllNames()
           deviceNameMap.value = nameMap
       } catch (error) {
           console.error('加载设备名称失败:', error)
       }
   }
   
  onMounted(async () => {
      // 加载设备名称映射
      await loadDeviceNames()
      getStateList()
  })
  // 删除报警信息
  const deleteState = async (rid:number) => {
     let {data: res}:{data:IhttpReturn} = await proxy.$adminHttp.delete("/admin/removeErrorRecord",{
      params: {
          rid
      }
  })
  if (res.code !== 200) return proxy.notifyWarning(res.msg)
  getStateList()
  proxy.notifySuccess(res.msg)
  }

  // 获取报警信息列表
  const getStateList = async () => {
      let params = { ...queryParmas }
      // 只传递有值的参数
      Object.keys(params).forEach(key => {
        if (params[key] === '' || params[key] === undefined) {
          delete params[key]
        }
      })
      let {data: res} = await proxy.$adminHttp.get("/admin/getErrorList",{
      params
  })
      total.value = res.data.total  //获取查询的总数
      stateList.value = res.data.data    // 数据列表
  }
 // 禁用日期
   const disabledDate = (time: Date) => {
      return time.getTime() > Date.now()
   }
// 按照日期进行查询
 const toSearch = () => {
      if (!queryParmas.queryDate) {
        // 如果日期为空，重置查询参数并查询所有
        queryParmas.page = 1
        queryParmas.pageSize = 10
        queryParmas.queryDate = ''
        queryParmas.queryType = ""
        queryParmas.keywords = ""
        getStateList()
        return
      }
      queryParmas.queryDate = new Date(queryParmas.queryDate).toLocaleDateString().replace(/\//g,'-')
      getStateList()
  }

  const labelList = ref([
      {
          label: "待解决",
          value: 0
      },
      {
          label: "进行中",
          value: 1
      },
      {
          label: "已解决",
          value: 2
      }
  ])

  // 配置程序
  const configExe = ref(false)

  const config_radio = ref(0) // 选中那个状态

  const current_rid = ref(0) // 选中的rid

  // 打开配置对话框
  const openConfig = function(state: number,rid: number) {
      config_radio.value = state
      current_rid.value = rid
      configExe.value = true

  }

  // 确认修改状态
  const confirm_update_state = async function() {
      let {data:res}: {data: IhttpReturn} = await proxy.$adminHttp.put("/admin/updateErrorState",{
          rid: current_rid.value,
          state: config_radio.value
      })
      if (res.code !== 200) return proxy.notifyWarning("修改状态失败")
      proxy.notifySuccess(res.msg)
      configExe.value = false
      getStateList()
  }

  // 通过状态进行查询
  const query_by_state = () => {
      if (queryParmas.queryType === '') return proxy.notifyWarning("请选择一种状态")
      if (queryParmas.queryDate) queryParmas.queryDate = new Date(queryParmas.queryDate).toLocaleDateString().replace(/\//g,'-')
      getStateList()
  }
  // 关键字查询
  const queryKeyword = () => {
    if (queryParmas.keywords === '') {
      // 如果关键字为空，重置查询参数并查询所有
      queryParmas.page = 1
      queryParmas.pageSize = 10
      queryParmas.queryDate = ''
      queryParmas.queryType = ""
      queryParmas.keywords = ""
      getStateList()
      return
    }
    queryParmas.page = 1
    queryParmas.pageSize = 10
    getStateList()
  }



  /*分页操作*/ 
  const handleSizeChange = (val:number) => {
      queryParmas.pageSize = val
      getStateList()
  }

  const handleCurrentChange = (val:number) => {
      queryParmas.page = val
      getStateList()
  }

  /*查询*/

</script>


<style lang="less" scoped>
@media screen and (max-width: 1024px) {
  .message {
    padding-bottom: 40px;
  }
}
/* 分页组件样式优化 */
.el-pagination {
  margin-top: 15px;
  padding: 15px 0;
  display: flex;
  justify-content: center;
  flex-shrink: 0; /* 确保分页器始终可见 */
  border-top: 1px solid #ebeef5; /* 添加顶部边框分隔 */
  background: #fafafa; /* 添加背景色突出显示 */
}
#state_update {
  font-size: 16px;
  position: relative;
  &::before {
      content: "";
      position: absolute;
      left: 0;
      width: 3px;
      height: 20px;
      background-color: #88cf64;
  }
}
  .message {
      padding:20px 20px 0px;
      height: calc(100vh - 80px); /* 计算总高度：视口高度减去头部导航高度 */
      display: flex;
      flex-direction: column;

     
      
  .tool {
      display: flex;
      justify-content: space-between;
      align-items: center;
      flex-shrink: 0; /* 防止工具栏被压缩 */
      margin-bottom: 20px;
    .query {
      margin-left: 10px;
    }
  }
}
.table {
  display: flex;
  flex-direction: column;
}

.table-container {
  flex: 1; /* 占据大部分空间 */
  overflow-y: scroll; /* 防止溢出 */
  min-height: 0;
  
  /* 为表格添加滚动条 */
  :deep(.el-table) {
    height: auto !important;
  }
  
  :deep(.el-table__body-wrapper) {
    overflow-y: auto !important;
    max-height: calc(100vh - 280px);
  }
}

/* 分页组件样式优化 */
.pagination-wrapper {
  flex-shrink: 0; /* 确保分页器始终可见 */
  padding: 15px 0;
  border-top: 1px solid #ebeef5; /* 添加顶部边框分隔 */
  background: #fafafa; /* 添加背景色突出显示 */
  margin-bottom: 40px;
  .el-pagination {
    display: flex;
    justify-content: center;
  }
}

.device-name {
  display: inline-block;
  max-width: 100%;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}
.circle {
  display: inline-block;
  width: 6px;
  height: 6px;
  border-radius: 50%;
  margin-right: 5px;
}
.circle-danger {
  .circle;
  background-color: #f56c6c;
}
.circle-primary {
  .circle;
  background-color: #79bbff;
}
.circle-success {
  .circle;
  background-color: #88cf64;
}
.selectType {
  width: 15%;
  display: flex;
}
</style>